package com.android.common.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import com.android.common.constant.Constant;
import com.android.common.utils.FileUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Assets 资源目录下的db文件拷贝到
 * data/data/packageName/database
 */
public class AssetsDBCreator extends SQLiteOpenHelper {
    private final String DB_PATH_IN_DATA_DIR;
    public AssetsDBCreator(Context context) {
        super(context, DBConfig.ASSETS_MANAGER_DATABASE_NAME, null, DBConfig.DATABASE_VERSION);
        DB_PATH_IN_DATA_DIR = context.getApplicationInfo().dataDir + "/databases/" + DBConfig.ASSETS_MANAGER_DATABASE_NAME;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        // do nothing
    }

    @Override
    public synchronized SQLiteDatabase getWritableDatabase() {
        copyAssetsDb2DataDir();
        return getAssetsManagerDatabase();
    }

    @Override
    public synchronized SQLiteDatabase getReadableDatabase() {
        copyAssetsDb2DataDir();
        return getAssetsManagerDatabase();
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    @Nullable
    private SQLiteDatabase getAssetsManagerDatabase(){
        SQLiteDatabase sqLiteDatabase = null;
        try {
            sqLiteDatabase = SQLiteDatabase.openDatabase(DB_PATH_IN_DATA_DIR, null, SQLiteDatabase.OPEN_READWRITE);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
        return sqLiteDatabase;
    }

    private void copyAssetsDb2DataDir(){
        try {
            File file = new File (DB_PATH_IN_DATA_DIR);
            if (file.exists()) return;
            String DB_PATH_IN_ASSETS_DIR = "databases/" + DBConfig.ASSETS_MANAGER_DATABASE_NAME;
            InputStream inputStream = Constant.GLOBAL_APPLICATION.getAssets().open(DB_PATH_IN_ASSETS_DIR);
            FileOutputStream outputStream = new FileOutputStream(DB_PATH_IN_DATA_DIR);
            FileUtil.writeIns2Outs(inputStream,outputStream);
        } catch (IOException fileNotFoundException){
            fileNotFoundException.printStackTrace();
        }
    }
}

